package com.example.demo.controller;

import com.example.demo.aop.ApiLog;
import com.example.demo.aop.Limit;
import com.example.demo.dto.LoginDto;
import com.example.demo.service.UserService;
import com.example.demo.util.CaptchaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private CaptchaUtils captchaUtils;

    @PostMapping("/login")
    public Object login(@RequestBody @Valid LoginDto dto) {
        return userService.createToken(dto);
    }

    /**
     * 刷新令牌
     */
    @PostMapping("/refreshToken")
    public Object refreshToken(HttpServletRequest request) {
        //从请求头中获取refreshToken
        String oldRefreshToken = request.getHeader("refreshToken");
        return userService.refreshToken(oldRefreshToken);
    }

    @PostMapping("/captcha")
    @Limit(permitsPerSecond = 100)
    @ApiLog(desc = "获取验证码")
    public Object captcha() {
        return captchaUtils.generate();
    }
}
